<template>
  <view>
    <web-view
      :src="src"
      @message="getMessage"
      bindmessage="getMessage"
      v-if="isWebview"
    ></web-view>
  </view>
</template>

<script>
import config from "@/config.js";
export default {
  components: {},
  data() {
    return {
      configData: "",
      src: "",
      active: 1,
      operate: "",
      isWebview: true,
      posterUrl: "",
      category: "",
    };
  },
  onLoad(options) {
    // #ifdef MP-WEIXIN
    //设置下方的Menus菜单，才能够让发送给朋友与分享到朋友圈两个按钮可以点击
    uni.showShareMenu({
      withShareTicket: true,
      menus: ["shareAppMessage", "shareTimeline"],
    });
    this.category = options.category;
    // #endif
  },
  onShow() {
    this.configData = config.new_applet_info;
    this.src =
      "https://www.zhenbiaow.com/wxh5/index.html#/pages/index/zbw?id=" +
      this.configData.appid +
      "&category=" +
      this.category;
  },
  // 设置分享方法
  onShareAppMessage(res) {
    let _this = this;
    // console.log("onShareAppMessage", res);
    if (this.configData.setUpSharing) {
      if (res.from === "button") {
        // 来自页面内分享按钮
        if (res.target.dataset.name === "shareBtn") {
          return {
            title: "【甄标网】一手标源直卖平台",
            path: "pages/index/index",
            // imageUrl: 'https://i.danews.cc/xcx/share/index_share.jpg',
          };
        }
      }
      if (res.from === "menu") {
        // 来自页面右上角分享
        return {
          title: "【甄标网】一手标源直卖平台",
          path: "pages/index/index",
          // imageUrl: 'https://i.danews.cc/xcx/share/index_share.jpg',
        };
      }
    }
  },
  methods: {
    getMessage(e) {
      let _this = this;
      let data = e.detail.data[0];
      // console.log("getMessage==>e", e)
      // console.log("getMessage==>data", data)
      if (e) {
        this.active = data.active;
        this.operate = data.operate;
        // this.isWebview = false;
        if (data.methods == "download_image") {
          if (this.operate == 1) {
            // _this.isWebview = true;
            _this.saveImg(data.imageData);
            // #ifdef MP-WEIXIN
            // #endif
            // #ifdef MP-BAIDU
            _this
              .base64ToTempFilePath(data.imageData)
              .then((tempFilePath) => {
                _this.posterUrl = tempFilePath;
                uni.setStorageSync("imageUrl", _this.posterUrl);
                this.saveImage(_this.posterUrl);
              })
              .catch((err) => {
                console.error("出错:", err);
              });
            // #endif
          } else {
            _this
              .base64ToTempFilePath(data.imageData)
              .then((tempFilePath) => {
                _this.posterUrl = tempFilePath;
                console.log("临时文件路径:", tempFilePath);
                console.log("_this.isWebview:", _this.isWebview);
                uni.setStorageSync("imageUrl", _this.posterUrl);
              })
              .catch((err) => {
                console.error("出错:", err);
              });
          }
          // uni.hideLoading();
          // if (this.operate == 2) {

          // }
          // if (this.operate == 3) {}
        }
      }
    },

    // 封装方法：base64 数据转临时文件路径
    base64ToTempFilePath(base64Data) {
      return new Promise((resolve, reject) => {
        try {
          // 提取 Base64 编码部分
          const base64 = base64Data.replace(/^data:image\/\w+;base64,/, "");

          // 获取文件系统管理器
          const fs = wx.getFileSystemManager();

          // 创建临时文件路径
          const tempFilePath =
            wx.env.USER_DATA_PATH + "/temp_image_" + Date.now() + ".png";

          // 将 Base64 数据转为 ArrayBuffer
          const arrayBuffer = wx.base64ToArrayBuffer(base64);

          // 写入文件
          fs.writeFile({
            filePath: tempFilePath,
            data: arrayBuffer,
            encoding: "binary",
            success: () => {
              resolve(tempFilePath); // 成功时返回临时文件路径
            },
            fail: (err) => {
              reject("文件写入失败: " + err);
            },
          });
        } catch (error) {
          reject("转换失败: " + error);
        }
      });
    },
    //保存图片 saveImage
    async saveImage(src) {
      let that = this;
      let imginfo = await uni.getImageInfo({
        src,
      });
      if (imginfo[1]) {
        uni.saveImageToPhotosAlbum({
          filePath: imginfo[1].path,
          success() {
            uni.showModal({
              title: "保存成功",
              content: "图片已成功保存到相册",
              showCancel: false,
            });
          },
          fail(rej) {
            uni.showModal({
              title: "保存失败",
              content: "图片保存失败请稍后再试",
              showCancel: false,
            });
          },
        });
      }
    },
    saveImg(img) {
      var _this = this;
      let timestamp = Date.now();
      uni.showLoading({
        title: "正在下载中...",
      });
      wx.getFileSystemManager().writeFile({
        filePath: wx.env.USER_DATA_PATH + "/" + timestamp + ".png", //这里先把文件写到临时目录里.
        data: img.slice(22), //注意这里
        encoding: "base64",
        success: (res) => {
          wx.saveImageToPhotosAlbum({
            filePath: wx.env.USER_DATA_PATH + "/" + timestamp + ".png", //这是把临时文件 保存到 相册, 收工
            success: (res) => {
              uni.hideLoading();
              setTimeout(function () {
                uni.showToast({
                  title: "下载成功，请到相册查看",
                  duration: 2000,
                  icon: "none",
                });
              }, 1000); //延迟时间
            },
            fail: (error) => {
              console.log(error);
              wx.showToast({
                title: "下载失败",
              });
            },
          });
        },
        fail: (error) => {
          console.log(error);
          wx.showToast({
            title: "服务正忙",
          });
        },
      });
    },
  },
};
</script>

<style lang="scss"></style>
